package com.xian.java.wc;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.FlatMapIterator;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.tuple.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class MyWC {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        DataSource<String> dataSource = env.readTextFile("E:/test/wc.txt");
        FlatMapOperator<String, String> operator1 = dataSource.flatMap(new FlatMapIterator<String, String>() {
            @Override
            public Iterator<String> flatMap(String line) throws Exception {
                String[] arr = line.split(" ");
                return Arrays.asList(arr).iterator();
            }
        });

        MapOperator<String, Tuple2<String,Long>> operator2 = operator1.map(new MapFunction<String, Tuple2<String,Long>>() {
            @Override
            public Tuple2<String,Long> map(String s) throws Exception {
                return new Tuple2(s, 1L);
            }
        });

        AggregateOperator<Tuple2<String, Long>> operator3 = operator2.groupBy(0).sum(1);

        operator3.print();
    }
}
